package com.uziot.bucket.file.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author shidt
 * @version V1.0
 * @className DownloadController
 * @date 2020-12-11 15:55:40
 * @description
 */
@Slf4j
@RestController
public class FileDownloadController {

    @GetMapping(value = "/download")
    public Object downloadFile(String url, HttpServletRequest request, HttpServletResponse response) {
        File file = new File(url);
        String fileName = UUID.randomUUID().toString() + "." + getExtend("filenam", "doc");
        // 设置文件名
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            log.error("文件下载出现异常，具体信息为：{}", e.toString());
        } finally {
            closeQuietly(bis);
            closeQuietly(fis);
        }

        return "下载完成！";
    }

    public static String getExtend(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > 0) && (i < (filename.length() - 1))) {
                return (filename.substring(i + 1)).toLowerCase();
            }
        }
        return defExt.toLowerCase();
    }

    /**
     * 关闭流
     *
     * @param closeable closeable
     */
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ignored) {
        }

    }
}
